package com.haixinga;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author terrfly
 * @Date 2019/11/7 15:50
 * @Description MybatisPlus 代码生成器
 **/
public class MybatisPlusGenerator {

    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "";
    private static final String AUTHOR = "mybatis-plus generator"; //作者注释

    public static final String[] GENERATOR_TABLE_NAMES = new String[]{  //生成的表名, 数组形式
            "t_haixinga_sys_user"
    };

    public static void main(String[] args) throws Exception {

        AutoGenerator mpg = new AutoGenerator();  //创建代码生成器对象

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        String userDir = System.getProperty("user.dir"); //User's current working directory
        String outputDir = userDir + "/src/test/java/com/haixinga/output/";
        gc.setOutputDir(outputDir);
        gc.setAuthor(AUTHOR);  //作者
        gc.setOpen(false); //自动打开目录
        gc.setFileOverride(true); //覆写已生成的文件
        gc.setDateType(DateType.ONLY_DATE); //使用 java.util.Date
        gc.setBaseResultMap(true); //自动生成BaseResultMap
        mpg.setGlobalConfig(gc);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(DB_URL);
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(DB_USERNAME);
        dsc.setPassword(DB_PASSWORD);

        // 自定义类型转换器, 将tinyint类型转换为 Byte类型, 其余类型参考MySqlTypeConvert
        ITypeConvert myTypeConvert = (globalConfig, fieldType) -> {
            String t = fieldType.toLowerCase();
            if (t.contains("tinyint(1)")) {
                return DbColumnType.BOOLEAN;
            }else if (t.contains("tinyint")) {
                return DbColumnType.BYTE;
            }else{
                return new MySqlTypeConvert().processTypeConvert(globalConfig, fieldType);
            }
        };
        dsc.setTypeConvert(myTypeConvert);
        mpg.setDataSource(dsc);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.haixinga.mvntemplate"); //所有包名的公共部分
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("ctrl");
        pc.setXml("mapper");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                String outFileName = outputDir + pc.getParent().replaceAll("\\.", "/") + "/" +
                        pc.getXml().replaceAll("\\.", "/") + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;

                return outFileName;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setCapitalMode(true); //数据库表名, 列名称为大写模式， generator将自动toLowerCase
        strategy.setNaming(NamingStrategy.underline_to_camel);  //no_change:不做任何改变，原样输出, underline_to_camel:下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        // 写于父类中的公共字段
        strategy.setInclude(GENERATOR_TABLE_NAMES);   //表名，多个英文逗号分割
        strategy.setControllerMappingHyphenStyle(true);     //驼峰转连字符
        strategy.setTablePrefix("t_haixinga_");  //表前缀
        mpg.setStrategy(strategy);

        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }




}
